//
//  ViewController.m
//  MultiThread
//
//  Created by Justsoso on 16/3/22.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "ViewController.h"

//#import <pthread.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

void * run (void *param)
{
//    for (int i=0; i<10000; i++)
//    {
//        NSLog(@"线程1：%i",i);
//    }
    NSLog(@"子线程1");
    return NULL;
}

void * run2 (void *param)
{
//    for (int i=0; i<10000; i++)
//    {
//        NSLog(@"线程2：%i",i);
//    }
    NSLog(@"子线程2");
    return NULL;
}

- (IBAction)btnPressed:(id)sender
{
    // 1. pthread 方式
//    pthread_t thread;
//    pthread_create(&thread, NULL, run, NULL);
//    
//    pthread_t thread2;
//    pthread_create(&thread2, NULL, run2, NULL);
    
    // 2. NSThread 方式
    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(multiThread:) object:@"子线程3"];
    [thread3 start];
    
    // 类方法创建
    [NSThread detachNewThreadSelector:@selector(multiThread:) toTarget:self withObject:@"子线程4"];
    
    // 3. GCD方式
    dispatch_queue_t queue2 = dispatch_queue_create("子线程5", NULL);
    
    dispatch_async(queue2, ^{
//        for (int i=0; i<10000; i++)
//        {
//            NSLog(@"子线程5：%i",i);
//        }
        NSLog(@"子线程5");
    });
    
    // 4. NSOperationQueue 线程池
    NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];
    [threadQueue addOperationWithBlock:^{
//        for (int i=0; i<10000; i++)
//        {
//            NSLog(@"子线程6：%i",i);
//        }
        NSLog(@"子线程6");
    }];
    
    NSOperationQueue *threadQueue2 = [[NSOperationQueue alloc] init];
    threadQueue2.maxConcurrentOperationCount = 2;
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(multiThread:) object:@"子线程7"];
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(multiThread:) object:@"子线程8"];
    NSInvocationOperation *op3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(multiThread:) object:@"子线程9"];
//    [threadQueue2 addOperation:op1];
//    [threadQueue2 addOperation:op2];
//    [threadQueue2 addOperation:op3];
    [threadQueue2 addOperations:@[op1,op2,op3] waitUntilFinished:NO];
    
    [self performSelectorInBackground:@selector(multiThread:) withObject:@"后台线程"];
}

- (void)multiThread:(NSString *)name
{
//    for (int i=0; i<10000; i++)
//    {
//        NSLog(@"%@：%i",name,i);
//    }
    NSLog(@"%@",name);
}

@end
